# -*- coding:UTF-8 -*-
from django.shortcuts import render
from django.http import JsonResponse
from django.forms.models import model_to_dict
from cmdb.views import *
import json
from diy_decorator.auth import *

from cmdb.base_database import *

from business_database.category_info_class import *
from business_database.business_info_class import *
from business_database.apply_business_log_class import *
from business_database.server_business_mapping_class import *
from cmdb.mequipment.equipment_database.system_info_class import update_status_system_info
from cmdb.mequipment.equipment_database.equipment_info_class import get_equipment_info
from business_database.approval_process_log_class import *
from business_database.buffer_class import *

from cmdb.mequipment.equipment_database.equipment_info_class import get_eno_equipment_info
from cmdb.mequipment.equipment_database.server_room_info_class import get_server_rooms

#分类页
@login_required()
def index(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    startpage=(page-1)*page_num
    endpage=startpage+page_num
    searchStr = request.GET.get('search','')
    categoryInfo = category_info(searchStr,startpage,endpage)
    count = categoryInfo['count']
    cRes = categoryInfo['category_info_list']
    cAllRes = get_category_infos()
    page_total = int(count/page_num)
    if (count%page_num) > 0:
        page_total += 1

    allCategoryArr = {}
    for singleC in cAllRes:
        allCategoryArr[singleC['id']] = singleC['category_name']
    for singleC in cRes:
        singleC.category_level = categoryLevel[singleC.grade]
        if singleC.parent_category > 0:
            singleC.parent_category_name = allCategoryArr[singleC.parent_category]
        else:
            singleC.parent_category_name = ''

    context={
        "category_list" : cRes,
        'search' : searchStr,
        'page_total' : page_total,
        'page_list' : range(1,page_total+1),
        'page' : page,
        'page_num' : page_num,
        'count' : count,
    }
    return render(request, 'cmdb/mbusiness/category.html', context)

#跳转添加分类页面
@login_required()
def caddinfo(request):
    grade = 1
    cAllRes = level_category_info(grade)
    finalArr = []
    for singleV in cAllRes:
        singleV['caterogy_level'] = categoryLevel[grade]
        finalArr.append(singleV)
    context = {
        'category_list' : finalArr,
    }
    return render(request, 'cmdb/mbusiness/category_add.html', context)

#添加分类
def caddaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    category_name = request.POST.get('category_name')
    parentCategory = request.POST.get('parent_category')
    str1,str2 = parentCategory.split(':')
    parent_category = int(str2)
    grade = int(str1)
    comment = request.POST.get('comment')
    operator = request.POST.get('operator')
    grade += 1
    try:
        add_category_info(category_name,grade,parent_category,comment,operator)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,":",ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#跳转编辑分类页面
@login_required()
def ceditinfo(request):
    context = {}
    id = request.GET.get('id')
    page = request.GET.get('page')
    try:
        context['category_info'] = get_category_info(id)
        cAllRes = exclude_level_category_info(1, id)
        finalArr = []
        for singleV in cAllRes:
            singleV['caterogy_level'] = categoryLevel[singleV['grade']]
            finalArr.append(singleV)
        context['category_list'] = finalArr
        context['page'] = page
    except Exception,ex:
        print Exception,ex
    return render(request, 'cmdb/mbusiness/category_edit.html', context)

#编辑分类
def ceditaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1}
    id = request.POST.get('id')
    category_name=request.POST.get('category_name')
    parentCategory = request.POST.get('parent_category')
    str1,str2 = parentCategory.split(':')
    parent_category = int(str2)
    grade = int(str1)
    comment = request.POST.get('comment')
    operator = request.POST.get('operator')
    grade += 1
    try:
        edit_category_info(id, category_name, grade, parent_category, comment, operator)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#删除分类
def cdeleteaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1,'module_manage' : 1}
    id = request.POST.get('id')
    grade = int(request.POST.get('grade'))
    try:
        if grade == 1:
            if exist_children_category_info(id):
                response_dict['status'] = 0
                response_dict['message'] = '存在子分类，不可删除'
            else:
                del_category_info(id)
        else:
            if exist_category_business_info(id):
                response_dict['status'] = 0
                response_dict['message'] = '存在此分类模块，不可删除'
            else:
                del_category_info(id)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#模块列表
@login_required()
def moduleinfo(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    searchStr = request.GET.get('search','')
    startpage=(page-1)*page_num
    endpage=startpage+page_num
    category = request.GET.get('category','all')
    if category == 'all':
        category = '0'
    category = int(category)
    businessInfo = business_info(category,searchStr,startpage,endpage)
    count = businessInfo['count']
    bRes = businessInfo['business_info_list']
    page_total = int(count/page_num)
    if (count%page_num) > 0 or page_total == 0:
        page_total += 1
    cAllRes = get_category_infos()
    allCategoryArr = {}
    for singleC in cAllRes:
        allCategoryArr[singleC['id']] = singleC
    for idx in allCategoryArr:
        categoryInfo = allCategoryArr[idx]
        if categoryInfo['parent_category'] > 0:
            parentCategory = allCategoryArr[categoryInfo['parent_category']]
            categoryInfo['parent_category_name'] = parentCategory['category_name']
        allCategoryArr[idx] = categoryInfo

    for singleC in bRes:
        categoryInfo = allCategoryArr[singleC.category]
        if categoryInfo['parent_category'] > 0:
            singleC.parent_category_name = categoryInfo['parent_category_name']
        singleC.category_name = categoryInfo['category_name']
    context={
        "module_list" : bRes,
        'category_list' : allCategoryArr,
        'page_total' : page_total,
        'page_list' : range(1,page_total+1),
        'page' : page,
        'page_num' : page_num,
        'count' : count,
        'search' : searchStr,
        'category' : category,
        'module_manage' : 1
    }
    return render(request, 'cmdb/mbusiness/business_list.html', context)

#跳转添加模块页面
@login_required()
def maddinfo(request):
    context = {'module_manage' : 1, 'page':request.GET.get('page')}
    try:
        id = request.GET.get('id')
        applyRes = get_apply_business_log(id)
        categoryRes = get_category_info(applyRes.category)
        applyRes.category_name = categoryRes.category_name
        parentCategoryRes = get_category_info(categoryRes.parent_category)
        applyRes.parent_category_name = parentCategoryRes.category_name
        context['apply_business_log_info'] = applyRes
        context['module_status_list'] = moduleStatusDict
    except Exception,ex:
        print Exception,ex
    return render(request, 'cmdb/mbusiness/operation_audit_add.html', context)

#添加模块
def maddaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1,'module_manage' : 1}
    id = request.POST.get('id')
    module_name = request.POST.get('module_name')
    category = request.POST.get('category')
    project = request.POST.get('project')
    application = request.POST.get('application')
    responser = request.POST.get('responser')
    responser_back = request.POST.get('responser_back')
    comment = request.POST.get('comment')
    operator = request.POST.get('operator')
    equipment_configure_info = request.POST.get('equipment_configure_info')
    decodeJson = json.loads(equipment_configure_info)
    sysInnerIpDict = {}
    set_transaction(False)
    try:
        cursor = get_cursor()
        module_no = add_business_info(module_name, category, project, application, comment, operator, responser, responser_back, cursor)
        for singleV in decodeJson:
            sConfigureArr = singleV.split(";")
            itemDict = {}
            for sConfigure in sConfigureArr:
                itemArr = sConfigure.split(":")
                if itemArr[1] and itemArr[1] == 'undefined':
                    itemDict[itemArr[0]] = ''
                else:
                    itemDict[itemArr[0]] = itemArr[1]
            if not sysInnerIpDict or not sysInnerIpDict.has_key(itemDict['sys_ip_inner']):
                tmpNo = get_eno_equipment_info(itemDict['sys_ip_inner'])
                if tmpNo:
                    sysInnerIpDict[itemDict['sys_ip_inner']] = tmpNo
                    itemDict['equipment_no'] = tmpNo
            else:
                itemDict['equipment_no'] = sysInnerIpDict[itemDict['sys_ip_inner']]
            if itemDict.has_key('equipment_no'):
                update_status_system_info(itemDict['equipment_no'],'1',cursor)
                add_server_mapping(module_no, itemDict['equipment_no'], str(itemDict['use_status']), itemDict['server_port'],
                                   itemDict['shutdown_port'], itemDict['jmx_port'], itemDict['outer_mapping_port'],
                                   itemDict['outline_port'], itemDict['application_path'], itemDict['configure_path'], operator, cursor)
        update_status_apply_log( id, '4', cursor)
        connection_commit()
    except Exception,ex:
        connection_rollback()
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
        print Exception,ex
    set_transaction(True)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#跳转编辑模块页面
@login_required()
def meditinfo(request):
    context = {
        'page':request.GET.get('page',1),
        'module_manage' : 1
    }
    module_no = request.GET.get('module_no')
    try:
        bInfo = get_business_info(module_no)
        bCategoryInfo = get_category_info(bInfo.category)
        bInfo.category_name = bCategoryInfo.category_name
        pCategoryInfo = get_category_info(bCategoryInfo.parent_category)
        bInfo.parent_category_name = pCategoryInfo.category_name
        context['module_info'] = bInfo
        businessMappingInfo = filter_server_mapping(module_no)
        idx = 0
        for singleMapping in businessMappingInfo:
            tmpEquipmentInfo = get_equipment_info(singleMapping.equipment_no)
            singleMapping.sys_ip_inner = tmpEquipmentInfo.sys_ip_inner
            singleMapping.number = idx
            idx += 1
        context['business_server_mapping'] = businessMappingInfo
        context['module_status_list'] = moduleStatusDict
        context['net_count'] = idx
    except Exception,ex:
        print Exception,ex
    return render(request, 'cmdb/mbusiness/operation_audit_edit.html', context)

#编辑模块，只可编辑备注，挂在设备启动类型，负责人，备负责人
def meditaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1,'module_manage' : 1}
    id = request.POST.get('id')
    moduleNo = request.POST.get('module_no')
    responser = request.POST.get('responser')
    responserBack = request.POST.get('responser_back')
    operator = request.POST.get('operator')
    equipment_configure_info = request.POST.get('equipment_configure_info')
    decodeJson = json.loads(equipment_configure_info)
    comment = request.POST.get('comment')
    sysInnerIpDict = {}
    set_transaction(False)
    try:
        cursor = get_cursor()
        #查询更新前所有挂载设备编号,待模块挂载更新后是否还有模块挂载在此设备下，如果没有将释放机器资源，设为为使用状态
        equipmentExists = filter_eno_server_mapping(moduleNo)
        #更新模块信息
        update_business_info(id, comment,operator, responser, responserBack, cursor)
        #更新挂载设备关联关系
        #新的设备关联关系
        newEquipmentNos = []
        del_server_mapping(moduleNo, cursor)
        for singleV in decodeJson:
            sConfigureArr = singleV.split(";")
            itemDict = {}
            for sConfigure in sConfigureArr:
                itemArr = sConfigure.split(":")
                if itemArr[1] and itemArr[1] == 'undefined':
                    itemDict[itemArr[0]] = ''
                else:
                    itemDict[itemArr[0]] = itemArr[1]
            if not sysInnerIpDict or not sysInnerIpDict.has_key(itemDict['sys_ip_inner']):
                tmpNo = get_eno_equipment_info(itemDict['sys_ip_inner'])
                if tmpNo:
                    sysInnerIpDict[itemDict['sys_ip_inner']] = tmpNo
                    itemDict['equipment_no'] = tmpNo
            else:
                itemDict['equipment_no'] = sysInnerIpDict[itemDict['sys_ip_inner']]
            if itemDict.has_key('equipment_no'):
                if itemDict['equipment_no'] not in newEquipmentNos:
                    update_status_system_info(itemDict['equipment_no'],'1',cursor)
                add_server_mapping(moduleNo, itemDict['equipment_no'], str(itemDict['use_status']), itemDict['server_port'],
                                   itemDict['shutdown_port'], itemDict['jmx_port'], itemDict['outer_mapping_port'],
                                   itemDict['outline_port'], itemDict['application_path'], itemDict['configure_path'], operator, cursor)

        #更新挂载关系后更新设备是否被使用状态
        for singleEquipment in equipmentExists:
            if singleEquipment.equipment_no not in newEquipmentNos:
                if not exist_module_server_mapping(singleEquipment.equipment_no):
                    update_status_system_info(singleEquipment.equipment_no,'0',cursor)
        connection_commit()
    except Exception,ex:
        connection_rollback()
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
        print Exception,ex
    set_transaction(True)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#获取模块及相关信息
def moduleget(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1,'module_manage' : 1,'data':{}}
    module_no = request.POST.get('module_no')
    try:
        mInfo = get_business_info(module_no)
        mArr = model_to_dict(mInfo, exclude=['is_active', 'is_stuff'])
        categoryInfo = get_category_info(mArr['category'])
        mArr['category_name'] = categoryInfo.category_name
        parentCInfo = get_category_info(categoryInfo.parent_category)
        mArr['parent_category_name'] = parentCInfo.category_name
        mappingArr = []
        serverIpDict = {}
        smappInfo = filter_eno_server_mapping(module_no)
        if smappInfo:
            for singleMapping in smappInfo:
                singleMappingArr = model_to_dict(singleMapping, exclude=['is_active', 'is_stuff'])
                equipment_no = singleMappingArr['equipment_no']
                if not serverIpDict or not serverIpDict.has_key(equipment_no):
                    equipmentInfo = get_equipment_info(equipment_no)
                    serverIpDict[equipment_no] = equipmentInfo.sys_ip_inner
                singleMappingArr['sys_ip_inner'] = serverIpDict[equipment_no]
                singleMappingArr['use_status_desc'] = moduleStatusDict[singleMappingArr['use_status']]
                mappingArr.append(singleMappingArr)
        response_dict['data']['business_info'] = mArr
        response_dict['data']['server_mapping_list'] = mappingArr
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#删除模块操作
def mdeleteaction(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1,'module_manage' : 1}
    id = request.POST.get('id')
    moduleNo = request.POST.get('module_no')
    try:
        if exist_eno_server_mappint(moduleNo):
            response_dict['status'] = 0
            response_dict['message'] = '存在执行模块，不可删除'
        else:
            del_business_info(id)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
        print Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#跳转模块申请页面
@login_required()
def mapply(request):
    context = { 'module_manage' : 1}
    try:
        cInfo = get_category_infos()
        firstCateArr = {}
        for category in cInfo:
            firstCateArr[category['id']] = {'info' : category,'sub_category':[]}
        for category in cInfo:
            if category['grade'] > 1:
                firstCateArr[category['parent_category']]['sub_category'].append(category)
        singleCateArr = {}
        finalCateArr = {}
        for idx in firstCateArr:
            if len(firstCateArr[idx]['sub_category']) > 0:
                if not singleCateArr:
                    singleCateArr = firstCateArr[idx]
                else:
                    finalCateArr[idx] = firstCateArr[idx]
        if singleCateArr is not None:
            context['category_info'] = singleCateArr
        if finalCateArr:
            context['category_list'] = finalCateArr
    except Exception,ex:
        print Exception,ex
    return render(request, 'cmdb/mbusiness/business_apply.html', context)

#模块申请
def mapplycation(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1,'module_manage' : 1}
    applier = request.POST.get('applier')
    depart_manger = request.POST.get('depart_manger')
    category = request.POST.get('category')
    parent_category = request.POST.get('parent_category')
    module_name = request.POST.get('module_name')
    module_number = request.POST.get('module_number')
    apply_server_number = request.POST.get('apply_server_number')
    description = request.POST.get('description')
    try:
        add_apply_business_log(applier, depart_manger, category, parent_category, module_name,module_number,
                               apply_server_number, 0, description)
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#模块申请列表
@login_required()
def mapplyinfo(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    startpage=(page-1)*page_num
    endpage=startpage+page_num
    statusStr = request.GET.get('status','all')
    searchStr = request.GET.get('search','')
    status = 100
    if statusStr != 'all':
        status = int(statusStr)
    applyBusinessLogInfo = apply_business_log(searchStr,status,startpage,endpage)
    count = applyBusinessLogInfo['count']
    aRes = applyBusinessLogInfo['apply_business_log_list']
    page_total = int(count/page_num)
    if (count%page_num) > 0 or page_total == 0:
        page_total += 1
    for singleV in aRes:
        singleV.status_desc = applyStatusDict[singleV.status]
        singleV.operate = 0
        if singleV.status == 0 or singleV.status == 1 or singleV.status == 2:
            singleV.operate = 1
    context={
        "apply_log_list" : aRes,
        'apply_status_list' : applyStatusDict,
        'page_total' : page_total,
        'page_list' : range(1,page_total+1),
        'page' : page,
        'page_num' : page_num,
        'count' : count,
        'status' : status,
        'search' : searchStr,
        'module_manage' : 1
    }
    return render(request, 'cmdb/mbusiness/apply_log.html', context)

#申请模块信息
def mgetinfo(request):
    if not request.session.has_key('username'):
        response=JsonResponse({'status':0,'message':'请做登录认证'},safe=False)
        response["CHARSET"]='UTF-8'
        return response
    response_dict = {"status":1,'module_manage' : 1}
    id = request.GET.get('id')
    try:
        aRes = get_apply_business_log(id)
        applyArr = model_to_dict(aRes, exclude=['is_active', 'is_stuff'])
        cRes = get_category_info(aRes.category)
        applyArr['category_name'] = cRes.category_name
        cRes = get_category_info(aRes.parent_category)
        applyArr['parent_category_name'] = cRes.category_name
        response_dict['data'] = applyArr
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#模块申请进度
def approvalProcess(request):
    response_dict = {"status":1,'module_manage' : 1}
    id = request.GET.get('id')
    try:
        if not exist_approval_process_log(id):
            add_approval_process_log(id)
        pRes = get_approval_process_log(id)
        finalArr = []
        for singleV in pRes:
            approval = model_to_dict(singleV, exclude=['is_active', 'is_stuff'])
            approval['status_desc'] = applyStatusDict[approval['status']]
            finalArr.append(approval)
        if finalArr:
            response_dict['data'] = finalArr
    except Exception,ex:
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
        print  Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#模块申请进度更新
def approvalUpdate(request):
    response_dict = {"status":1,'module_manage' : 1}
    id = request.POST.get('id')
    status = request.POST.get('status')
    set_transaction(False)
    try:
        cursor = get_cursor()
        applyId = get_apply_id_approval_process(id)
        update_approval_process_log(id,status,cursor)
        allRes = get_approval_process_log(applyId)
        resStatus = 0
        for singleV in allRes:
            if singleV.status == 3:
                resStatus = 3
                break
            if singleV.status == 2:
                resStatus += 1
        if resStatus > 0:
            update_status_apply_log(applyId, str(resStatus), cursor)
        connection_commit()
    except Exception,ex:
        connection_rollback()
        response_dict['status'] = 0
        response_dict['message'] = Exception,ex
        print Exception,ex
    set_transaction(True)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#buffer池列表
@login_required()
def buffer(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    context = {}
    try:
        startpage=(page-1)*page_num
        bufferInfo = buffer_info(startpage,page_num)
        count = bufferInfo['count']
        equipmentList = bufferInfo['buffer_list']
        page_total = int(count/page_num)
        if (count%page_num) > 0 or page_total == 0:
            page_total += 1

        roomRes = get_server_rooms()
        roomDict = {}
        for singleRoom in roomRes:
            roomDict[singleRoom['id']] = singleRoom['server_room']
        for i in range(0, len(equipmentList)):
            singleV = equipmentList[i]
            singleV['server_room'] = roomDict[singleV['server_room_id']]
            singleV['equipment_type_desc'] = equipmentTypeDict[singleV['equipment_type']]
            equipmentList[i] = singleV

        context={
            "equipment_list" : equipmentList,
            'page_total' : page_total,
            'page_list' : range(1,page_total+1),
            'page' : page,
            'page_num' : page_num,
            'count' : count
        }
    except Exception,ex:
        print Exception,ex
    return render(request, 'cmdb/mbusiness/buffer.html', context)

def moduleUniqueCheck(request):
    response_dict = {"status":1}
    category = request.POST.get('category','')
    moduleName = request.POST.get('module_name','')
    if category != '' and moduleName != '':
        try:
            if exist_business_info(category,moduleName):
                response_dict['data'] = True
                response_dict['module_status'] = 4
            elif exist_apply_business_log(category, moduleName):
                response_dict['data'] = True
                response_dict['module_status'] = 1
            else:
                response_dict['data'] =False
        except Exception,ex:
            response_dict['status'] = 0
            response_dict['message'] = Exception,ex
            print Exception,ex
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response
